<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/27 0027
 * Time: 15:52
 */

namespace Api\Service;

/**
 * 订单管理类
 * Class OrderService
 * @package Api\Service
 */
class OrderService
{
//    protected $order_table = 'AdOrder';
//    protected $order_list_table = 'AdOrderList';
    protected static $config = array();
    protected static $order_list_table = 'AdOrderList';
    protected static $order_table = 'AdOrder';
    public function __construct()
    {
        $config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
        }
        self::$config = $config;
    }

    /**
     * 订单结算
     * 曝光类统一结算 引流类在用户领取红包的时候结算 所以这里只结算曝光类广告
     */
    public static function autoSettlement()
    {
    	$config =   S('DB_CONFIG_DATA');
        if(!$config){
            $config =   api('Config/lists');
        }
        self::$config = $config;
        foreach (M(self::$order_table)->where(['settlement_status' => '0','ad_type' => '1'])->select() as $orderList) {
            //开始结算
            //做个记录
            $time = date('Y-m-d H:i:s');
            try{
                $shop_ratio = self::$config['UP_SHOP_LIMIT'];
                $shop_amount = floor($orderList['total_price'] * $shop_ratio * 100)/100;
                file_put_contents('order_settlement.log',"[{$time}]订单{$orderList['order_no']}开始结算,订单金额：{$orderList['total_price']} - {$shop_ratio}".PHP_EOL,FILE_APPEND);
                $ad_order_list = M(self::$order_list_table)->where(['order_no' => $orderList['order_no']])->find();
                $shop_id = $ad_order_list['shop_id'];
                $shop_info = M('Shop')->where(['id' => $shop_id,'status' =>'2'])->find();
                if(empty($shop_info)){
                    file_put_contents('order_settlement.log',"[{$time}]订单{$orderList['order_no']}跳过结算：商户信息查询失败".PHP_EOL,FILE_APPEND);
                    continue;
                }
                file_put_contents('order_settlement.log',"[{$time}]订单{$orderList['order_no']}开始结算,金额：{$shop_amount}".PHP_EOL,FILE_APPEND);
                M()->startTrans();// 开启事务
                //添加商户余额
                $shop_save_data = [
                    'balance' => $shop_info['balance'] + $shop_amount,
                    'shop_balance' => $shop_info['shop_balance'] + $shop_amount,
                    'exposure_balance' => $shop_info['exposure_balance'] + $shop_amount,
                    'withdraw_balance' => $shop_info['withdraw_balance'] + $shop_amount
                ];
                $shop_result = M('Shop')->where(['id' => $shop_id])->save($shop_save_data);
                $order_result = M(self::$order_table)->where(['id' => $orderList['id']])->save([
                    'settlement_status' => '1',
                    'settlement_at' => date('Y-m-d H:i:s')
                ]);
                $record_result = M('ShopMoneyRecord')->add([
                	'title' => '定向曝光',
                	'money' => $shop_amount,
                	'shop_id' => $shop_id,
                	'addtime' =>　time()
                ]);
                $distribution_result = true;
                $shop_usermember = M('Usermember')->where(['id' => $shop_info['user_id']])->find();
                if(!empty($shop_usermember) && $shop_usermember['pid'] != '0'){

                    $parent_usermember = M('Usermember')->where(['id' => $shop_usermember['pid']])->find();
                    if(!empty($parent_usermember)){
                        $parent_shop = M('Shop')->where(['user_id' => $parent_usermember['id'],'status' =>'2'])->find();
                        if(!empty($parent_shop)){
                            //计算下单次数
                            $parent_shop_order_num = M('AdOrder')->where(['mid' => $orderList['mid'],['status' => '1']])->count();
                            $distribution_ratio = return_proportion($parent_shop_order_num);
                            $distribution_price = floor($orderList['price'] * $distribution_ratio * 100)/100;
                            $distribution_result = M('Shop')->where(['id' => $parent_shop['id']])->save([
                                'balance' => $parent_shop['balance'] + $distribution_price,
                                'shop_balance' => $parent_shop['shop_balance'] + $distribution_price,
                                'exposure_balance' => $parent_shop['exposure_balance'] + $distribution_price,
                                'withdraw_balance' => $parent_shop['withdraw_balance'] + $distribution_price
                            ]);
                        }
                    }

                }
                if($shop_result !== false && $order_result !== false && $distribution_result !== false){
                    M()->commit();
                } else {
                    M()->rollback();
                }
            } catch (\Exception $e) {
                file_put_contents('order_settlement.log',"[{$time}]订单{$orderList['order_no']}执行结算失败, {$e->getMessage()}".PHP_EOL,FILE_APPEND);
            }
        }
    }

    /**
     * 上传广告
     * @return array|bool|string
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public static function autoAddItem()
    {
        foreach (M(self::$order_table)->where(['status' => '1','upload_status' => '0'])->select() as $order) {

            $res = AdDeployService::instance()->addItem([
                '广告-'.$order['order_no'],
                thumb_path($order['resource_id']),
                filesize(thumb_path($order['resource_id'])),
                (int)$order['ad_type']
            ]);
            //如果上传成功，修改广告上传状态
            //todo::包含二维码的上传
            if(isset($res['result']) && $res['result'] === 'success'){
                M(self::$order_table)->where(['id' => $order['id']])->save([
                    'upload_status' => '1',
                    'upload_id' => $res['id']
                ]);
            }
        }
    }

    /**
     * 广告自动部署
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     */
    public function deploy()
    {
        foreach (M(self::$order_list_table)->join('__AD_ORDER__ ON __AD_ORDER_LIST_.order_no = __AD_ORDER__.order_no')->where(['status' => '1','deploy_status' => '0'])->select() as $order) {
            $res = AdDeployService::instance()->deploy();
            //如果部署成功，修改广告部署状态
            if(isset($res['result']) && $res['result'] === 'success'){
                M(self::$order_list_table)->where(['id' => $order['id']])->save([
                    'deploy_status' => '1'
                ]);
            }

        }
    }
}